package com.gitee.ywj1352.算法.week01;

import java.util.HashMap;

public class 无重复字符的最长字串 {


    public static int lengthOfLongestSubstring(String s) {
        if (s.length() < 2) return s.length();
        HashMap<Character, Integer> map = new HashMap<>();
        int res = 0;
        int left = 0;
        for (int right = 0; right < s.length(); right++) {
            Integer idx = map.get(s.charAt(right));
            if (idx != null) {
                left = Math.max(left, idx);
            }
            map.put(s.charAt(right), right + 1);
            res = Math.max(res, right - left + 1);

        }
        return res;
    }

    public int lengthOfLongestSubstring2(String s) {
        int n = s.length(), ans = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int end = 0, start = 0; end < n; end++) {
            char alpha = s.charAt(end);
            if (map.containsKey(alpha)) {
                start = Math.max(map.get(alpha), start);
            }
            ans = Math.max(ans, end - start + 1);
            map.put(s.charAt(end), end + 1);
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("pwwkew"));
    }
}
